import { createAxios } from '@vc/request';
import { RequestEnum } from '@vc/request/src/constants';
import { formatRequestDate, joinTimestamp } from '@vc/request/src/helper';
import { AesEncryption, isFunction, isString, setObjToUrlParams } from '@vc/utils';

/** 默认 Pc header */
const CLIENT_PARAM = { client: 'PC' };

const encryptUrls = ['/ep-query'];
const encryptUrl = '/ep-query/doAction';
const encryptKey = 'DaoGuangJianYing';

export const request = createAxios({
  headers: {
    ...CLIENT_PARAM
  },
  requestOptions: {
    errorMessageCustom: true,
    ignoreCancelToken: false
  },
  transform: {
    beforeRequestHook: (config, options) => {
      const { joinParamsToUrl, formatDate, joinTime = true, urlPrefix } = options;
      let { apiUrl } = options;
      if (urlPrefix) {
        config.url = `${urlPrefix}${config.url}`;
      }
      
      let isEncrypt = false;
      for (const item of encryptUrls) {
        if (config.url!.includes(item)) {
          isEncrypt = true;
        }
      }
      
      if (!isEncrypt || import.meta.env.VITE_TRANSFORM_API === 'false') {
        if (apiUrl) {
          const _apiUrl = isString(apiUrl) ? apiUrl : isFunction(apiUrl) ? apiUrl?.() : '';
          config.url = `${_apiUrl}${config.url}`;
        }
        const params = config.params;
        const data = config.data || false;
        
        formatDate && data && !isString(data) && formatRequestDate(data);
        
        if (config.method?.toUpperCase() === RequestEnum.GET) {
          if (!isString(params)) {
            config.params = Object.assign(params || {}, joinTimestamp(joinTime, false));
          } else {
            config.url = config.url + params + `${joinTimestamp(joinTime, true)}`;
            config.params = undefined;
          }
        } else {
          if (!isString(params)) {
            formatDate && formatRequestDate(params);
            if (Reflect.has(config, 'data') && config.data && (Object.keys(config.data).length > 0 || config.data instanceof FormData)) {
              config.data = data;
              config.params = params;
            } else {
              config.data = params;
              config.params = undefined;
            }
            if (joinParamsToUrl) {
              config.url = setObjToUrlParams(config.url as string, Object.assign({}, config.params, config.data));
            }
          } else {
            config.url = config.url + params;
            config.params = undefined;
          }
        }
        return config;
      } else {
        if (apiUrl) {
          apiUrl = isString(apiUrl) ? apiUrl : isFunction(apiUrl) ? apiUrl?.() : '';
        }
        
        const { url, params } = config;
        
        const _parmas = { url, ...params };
        
        const keyArr: string[] = [];
        
        for (const key in _parmas) {
          if (_parmas[key]) {
            keyArr.push(key);
          }
        }
        
        console.log('加密的接口 url:', url, 'parmas', params);
        
        let data = `method=${config.method!.toLowerCase()}&`;
        
        for (const item of keyArr.sort()) {
          data += item + '=' + _parmas[item] + '&';
        }
        
        const aes = new AesEncryption({ key: encryptKey });
        
        data = data.replace(/&$/, '');
        
        config.data = {
          data: aes.encryptByAES(data)
        };
        
        config.url = apiUrl + encryptUrl;
        
        config.method = 'POST';
        config.params = undefined;
        
        return config;
      }
    }
  }
});
